var api = require('./../../config/api.js');
var app = getApp();
var util = require('./../../utils/util.js');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    isKnight: false,
    jumpInfo: false, //{page: 'detail', name: 'aoId', id:'1'}
    isFirst: false,
    isHaveBanner: false,
    //图片
    hdimg: [],
    //是否采用衔接滑动
    circular: true,
    //是否显示画板指示点
    indicatorDots: true,
    //选中点的颜色
    // indicatorcolor: "#000",
    //是否竖直
    vertical: false,
    //是否自动切换
    autoplay: true,
    //滑动动画时长毫秒
    duration: 500,
    //所有图片的高度
    imgheights: [],
    //图片宽度
    imgwidth: 750,
    //默认
    current: 0,
    animationData: {},
    onlineNum: '1',
    onlineText: '位骑士在线',
    isShowToast: true,
    isShowTakeout: 0,
    isShowShop: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    
    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
      wx.showToast({
        title: '新版本更精彩哦！',
        icon: 'none',
        duration: 2000
      })
    })
    
    console.log(options);
    console.log(app.globalData.userInfo);
    if (options.shareId){
      app.globalData.shareId = options.shareId;
    }
    if (options.url){
      this.setData({ jumpUrl: options.url});
    }

    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    
    this.waitGetUserInfo();
  },

  onLoadContinue: function () {
    
    var that = this;

    if (app.globalData.hdimg){
      if (app.globalData.hdimg.length > 0){
        that.setData({ hdimg: app.globalData.hdimg, isHaveBanner: true });
      }
    }
    
    // 是否注册了个人信息
    if (!app.globalData.userInfo.addition) {
      wx.redirectTo({
        url: './../userInfo/userInfo?shareId=' + app.globalData.shareId
      })
      return;
    }

    this.setData({userInfo: app.globalData.userInfo});
    if (app.globalData.knight){
      this.setData({ isKnight: true});
    }

    // 是否外部链接进入后跳转
    if (this.data.jumpInfo){
      app.globalData.first = 1;
      if (this.data.jumpInfo.page = 'detail'){
        wx.navigateTo({
          url: './../detail/detail?' + this.data.jumpInfo.name + '=' + this.data.jumpInfo.id
        })
      }
      return;
    }

    // 是否是快递员登录
    if (app.globalData.courier) {
      app.globalData.first = 1;
      wx.redirectTo({
        url: './../courier/courier'
      })
      return;
    }
    

    // 是否是骑士登录
    if (!app.globalData.first && app.globalData.knight){
      app.globalData.first = 1;
      wx.redirectTo({
        url: './../knight/knight'
      })
      return;
    }

    if (!app.globalData.first && app.globalData.schoolInfo.csShop){
      app.globalData.first = 1;
      this.toShop();
    }

    that.showOnlineToast();
    this.setData({ 
      isShowTakeout: app.globalData.schoolInfo.csTakeout,
      isShowShop: app.globalData.schoolInfo.csShop
    });

    try {
      var hasCome = wx.getStorageSync('hasCome');
      if (hasCome) {
        this.setData({ isFirst: false});
      }else{
        this.setData({ isFirst: true });
      }
    } catch (e) {
      // Do something when catch error
      this.setData({ isFirst: true });
    }
  },

  showOnlineToast: function(){
    var that = this;
    var getOnlineNumUrl = api.OnlineNum + '/' + app.globalData.userInfo.addition.uCustomInfo.csId;
    util.myRequest(getOnlineNumUrl, false, function (data) {
      //that.setData({ toDoNum: data.data.toDoNum, knightInfo: data.data.knight })
      var result = data.data;
      if (result < 0) {
        that.setData({
          onlineNum: '',
          onlineText: data.msg,
        });
      } else {
        that.setData({
          onlineNum: Object.keys(result).length,
        });
      }
      that.onlineToast(0, 8);
    }); 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.userInfo && !app.globalData.knight){
      app.wxLogin()
      wx.hideLoading();
      setTimeout(function(){
        wx.hideLoading();
      }, 200);
      setTimeout(function(){
        wx.hideLoading();
      }, 400);
      setTimeout(function(){
        wx.hideLoading();
      }, 600);
		}
  },

  onlineToast: function(index, max){
    var that = this;
    if (index == max){
      return;
    }
    that.setData({isShowToast: false});
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })

    //this.animation = animation

    animation.opacity(0.93).step()

    this.setData({
      animationData: animation.export()
    })

    setTimeout(function () {
      animation.opacity(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 4000)


    setTimeout(function () {
      that.onlineToast(index + 1, max);
    }, 5000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.globalData.shareInfo;
  },

  /**
   * 等待加载用户信息
   */
  waitGetUserInfo: function(){
    var that = this;
    //console.log('waitGetUserInfo');
    // 是否加载完成
    if (app.globalData.getUserDone == 0) {

      setTimeout(function () {
        that.waitGetUserInfo();
      }, 200);
    }else{
      wx.hideLoading();
      // 是否有注册信息
      if (!app.globalData.userInfo.uName){
        // wx.redirectTo({
        //   url: './../login/login'
        // })
        wx.redirectTo({
          url: './../userInfo/userInfo'
        })
      }else{
        that.onLoadContinue();
      }
    }
  },

  /**
   * 个人信息
   */
  goUserInfo: function() {
    wx.navigateTo({
      url: './../userInfo/userInfo?redirectTo=/pages/index/index'
    })
  },

  /**
   * 在线骑士
   */
  goKnightInfo: function () {
    wx.navigateTo({
      url: './../knightOnline/knightOnline'
    })
    return;
    if (this.data.onlineNum != ''){
      wx.navigateTo({
        url: './../knightOnline/knightOnline'
      })
    }
  },

  toBapuShop: function (){
    wx.navigateTo({
      //把shop/shop 缓存home/index
      url: './../home/index?url=bapu'
    })
  },

  /**
   * 代取快递
   */
  toTake: function () {
    if (this.checkInfo()){
      wx.navigateTo({
        url: './../take/take'
      })
    }
  },

  /**
   * 订单列表
   */
  toOrder: function () {
    wx.switchTab({
      url: './../user_order/order'
    })
  },

  toRun: function () {
    wx.navigateTo({
      url: './../errand/errand'
    })
  },

  toBuy: function () {
    if (this.checkInfo()) {
      wx.navigateTo({
        url: './../errand/buy/buy'
      })
    }
  },

  /**
   * 店铺街
   */
  toShop: function () {
     //把shop/shop 缓存home/index
    wx.switchTab({
      url: './../home/index'
    })
  },

  /**
   * 建议
   */
  toEvaluate: function () {
    wx.navigateTo({
      url: './../evaluate/evaluate'
    })
  },

  goFaq: function() {
    wx.navigateTo({
      url: './../faq/faq'
    })
  },
  goBluePrinter: function() {
    wx.navigateTo({
      url: './../bluePrinter/bluePrinter'
    })
  },
  

  /**
   * 骑士
   */
  toKnight: function () {

    if(!this.checkInfo()){
      return;
    }

    // 判断是否是骑士
    if (this.data.isKnight){
      wx.redirectTo({
        url: './../knight/knight'
      })
    }else{
      if (!app.globalData.knightApply){
        // 跳转到骑士申请
        // wx.navigateTo({
        //   url: './../apply/apply'
        // })
        wx.navigateTo({
          url: './../applyDetail/applyDetail'
        })
        return;
      }
      
      if (app.globalData.knightApply.kaStatus == 0){
        wx.navigateTo({
          url: './../wait/wait'
        })
      } else if (app.globalData.knightApply.kaStatus == 1){
        wx.redirectTo({
          url: './../knight/knight'
        })
      } else if (app.globalData.knightApply.kaStatus == 2) {
        wx.navigateTo({
          url: './../refuse/refuse'
        })
      }
    }
  },

  hidePopup: function(){
    wx.setStorage({
      key: "hasCome",
      data: true
    });
    this.setData({ isFirst: false });
  },

  showPopup: function () {
    this.setData({ isFirst: true });
  },

  // 检查信息
  checkInfo: function () {
    if (app.globalData.userInfo.addition.uCustomInfo.csId == 0){
      var that = this;

      wx.showToast({
        title: '请先完善个人信息',
        icon: 'none',
        duration: 900,
        mask: true,
      });

      setTimeout(function(){
        that.goUserInfo();
      }, 900);
      return false;
    }
    return true;
  },

  imageLoad: function (e) {
    //获取图片真实宽度
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比
      ratio = imgwidth / imgheight;
    console.log(imgwidth, imgheight)
    //计算的高度值
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight
    var imgheights = this.data.imgheights
    //把每一张图片的高度记录到数组里
    imgheights.push(imgheight)
    this.setData({
      imgheights: imgheights,
    })
  },
  bindchange: function (e) {
    //console.log(e.detail.current)
    this.setData({ current: e.detail.current })
  },

  bannerClick: function(event){
    console.log(event.currentTarget.id)
    for (var i = 0; i < this.data.hdimg.length;i++){
      if (this.data.hdimg[i].sbId == event.currentTarget.id){
        wx.setStorage({
          key: "bannerContent",
          data: this.data.hdimg[i].sbText
        })
        wx.navigateTo({
          url: './../text/text'
        })
        return;
      }
    }
  },
})